//
//  CWCVoideViewController.m
//  ChuanNews
//
//  Created by dllo on 16/4/14.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "CWCVoideViewController.h"
#import "BaseHeader.h"
#import "CWCVideoModel.h"
#import "CWCVideoCell.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
@interface CWCVoideViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *videoArray;
@property(nonatomic, retain)NSMutableArray *arrayMp4;
@property(nonatomic, retain)MBProgressHUD *hud;
@property(nonatomic, assign) BOOL isUpLoading;
@property(nonatomic, retain)UILabel *titleLabel;
@property(nonatomic, retain)NSIndexPath *indexPath;
@property(nonatomic, retain)NSIndexPath *selectedIndexPath;
@property(nonatomic, assign)CGRect selectedRect;
@property(nonatomic, retain)MPMoviePlayerViewController *mpPVC;
@property(nonatomic, copy)NSString *ti;
@property(nonatomic, assign)NSInteger page;
@end

@implementation CWCVoideViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"视频";
    self.videoArray = [NSMutableArray array];
    self.arrayMp4 = [NSMutableArray array];
    
    //加载菊花
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"loading......";
    self.hud.detailsLabelText = @"网络正在加载,请稍后......";
    self.hud.color = [UIColor blackColor];
    self.hud.dimBackground = YES;
    self.page = 10;
    [self creatDataWith:self.page];
    [self creatView];
    self.isUpLoading = NO;
    [self addFooter];
    [self addHeader];
    
}
//上拉刷新
- (void)addHeader{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.isUpLoading = NO;
        [self creatDataWith:self.page];
        
    }];
}
//下拉加载
- (void)addFooter {
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.isUpLoading = YES;
        self.page += 10;
        [self creatDataWith:self.page];
        
    }];
}
#pragma mark - 数据解析
- (void)creatDataWith:(NSInteger)page{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:[NSString stringWithFormat:@"http://c.3g.163.com/nc/video/Tlist/T1457068979049/%ld-10.html",self.page] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (self.isUpLoading == NO) {
            [self.videoArray removeAllObjects];
        }
        NSArray *Array = [responseObject objectForKey:@"T1457068979049"];
        for (NSDictionary *dic in Array) {
            CWCVideoModel *vid = [[CWCVideoModel alloc]initWithDic:dic];
            [self.videoArray addObject:vid];
            [self.arrayMp4 addObject:[dic objectForKey:@"mp4_url"]];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.hud hide:YES afterDelay:0];
            [self.tableView.mj_footer endRefreshing];
            [self.tableView.mj_header endRefreshing];
        });
        NSLog(@"%ld",self.arrayMp4.count);
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
}
#pragma mark-视图创建
-(void)creatView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    [self.tableView registerClass:[CWCVideoCell class] forCellReuseIdentifier:@"VideoTableViewCell"];
}

#pragma mark - tableView必须实现的方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  self.videoArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    self.indexPath = indexPath;
    CWCVideoModel *vid = [self.videoArray objectAtIndex:self.indexPath.row];
    CWCVideoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"VideoTableViewCell"];
    self.titleLabel.text = vid.title;
    self.ti = vid.title;
    
    cell.titleLabel.text = vid.title;
    cell.videosourceLabel.text = vid.videosource;
    cell.descLabel.text = vid.myDescription;
    NSString *str = vid.ptime;
    NSString *string = [str substringFromIndex:5];
    cell.timeLabel.text = string;
    NSString *countStr = [NSString stringWithFormat:@"%@看过", vid.playCount.description];
    cell.playCountLabel.text = countStr;
    [cell.imageCover setImageWithURL:[NSURL URLWithString:vid.cover]];
    cell.play.image = [UIImage imageNamed:@"voide.png"];
    //添加手势(点击封面图片,实现视频播放)
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [cell.imageCover addGestureRecognizer:tap];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"gb.png"] forState:UIControlStateNormal];
    
    button.backgroundColor = [UIColor clearColor];
    button.frame = CGRectMake(self.mpPVC.view.frame.size.width - 20, 0, 20, 20);
    [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.mpPVC.view addSubview:button];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 300;
}
#pragma mark - 右下角窗口退出按钮的点击事件
- (void)buttonAction{
    [self.mpPVC.moviePlayer stop];
    [self.mpPVC.view removeFromSuperview];
}
#pragma mark - 实现手势轻点的点击事件
- (void)tapAction:(UITapGestureRecognizer *)tap {
    if (self.mpPVC.view) {
        [self.mpPVC.view removeFromSuperview];
    }
    
    UIView *view = tap.view;
    UITableViewCell *cell = (UITableViewCell *)view.superview.superview;
    
    self.selectedIndexPath = [self.tableView indexPathForCell:cell];
    CWCVideoModel *model = self.videoArray[self.selectedIndexPath.row];
    self.mpPVC = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:model.mp4_url]];
    
    self.mpPVC.view.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 300);
    
    [self.mpPVC.moviePlayer setScalingMode:MPMovieScalingModeAspectFill];
    [self.mpPVC.moviePlayer setControlStyle:MPMovieControlStyleEmbedded];
    [cell addSubview:self.mpPVC.view];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"gb.png"] forState:UIControlStateNormal];
    
    button.backgroundColor = [UIColor clearColor];
    button.frame = CGRectMake(self.mpPVC.view.frame.size.width - 20, 0, 20, 20);
    [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.mpPVC.view addSubview:button];
}
#pragma mark - 右下角出现窗口的方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    CWCVideoCell *cell = (CWCVideoCell * )[self.tableView cellForRowAtIndexPath:self.selectedIndexPath];
    //当前cell在tableView上的坐标
    CGRect rectInTableView = [self.tableView rectForRowAtIndexPath:self.selectedIndexPath];
    CGRect rectInWindow = [self.tableView convertRect:rectInTableView toView:[self.tableView superview]];
    self.selectedRect = CGRectMake(rectInTableView.origin.x, rectInTableView.origin.y, cell.imageCover.bounds.size.width + 20, cell.imageCover.bounds.size.height + 20);
    if ([self.mpPVC.moviePlayer isPreparedToPlay]) {
        if (rectInWindow.origin.y <= -300 || rectInWindow.origin.y >= [UIScreen mainScreen].bounds.size.height) {
            [UIView animateWithDuration:0.5 animations:^{
                
                self.mpPVC.view.frame = CGRectMake(self.view.bounds.size.width - 170, self.view.bounds.size.height - 170, 170, 170);
                [self.view.window addSubview:self.mpPVC.view];
                self.mpPVC.moviePlayer.controlStyle = MPMovieControlStyleEmbedded;
                
            }];
            
        } else {
            self.mpPVC.view.frame = self.selectedRect;
            [self.tableView addSubview:self.mpPVC.view];
            self.mpPVC.moviePlayer.controlStyle = MPMovieControlStyleDefault;
        }
    }
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
